<template>
  <el-form label-width="100px" style="width: 500px">
    <el-form-item label="头像">
      <img v-if="fileList.length==0&&user.imgUrl!=null" :src="'http://localhost:8080'+user.imgUrl"
           style="width: 146px;height:146px; border-radius: 5px">
      <!--   上传组件开始   -->
      <el-upload
          v-model:file-list="fileList"
          name="file"
          :limit="1"
          action="http://localhost:8080/v1/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--   上传组件结束   -->
    </el-form-item>
    <el-form-item label="昵称">
      <el-input placeholder="请输入昵称" v-model="user.nickname"></el-input>
    </el-form-item>
    <el-form-item label="用户名">
      <el-input :value="user.username" disabled></el-input>
    </el-form-item>
    <el-form-item><el-button type="primary" @click="save()">保存修改</el-button></el-form-item>
  </el-form>
</template>

<script  setup>
import { ref } from 'vue'
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
const save = ()=>{
  //取出图片路径
  if (fileList.value.length>0){
    let imgUrl = fileList.value[0].response.data;
    //把上传成功的图片路径存到user对象里面
    user.value.imgUrl = imgUrl;
  }

  let data = qs.stringify(user.value);
  axios.post('http://localhost:8080/v1/users/update',data)
      .then((response)=>{
        if (response.data.code==2001){
          ElMessage.success("修改完成!");
          //更新LocalStorage里面的用户数据
          localStorage.user = JSON.stringify(user.value);
          location.href='/personal/index';
        }
      })
}
const user = ref(localStorage.user?JSON.parse(localStorage.user):null);


/*上传组件开始*/
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {

  axios.post('http://localhost:8080/v1/remove?imgUrl='+uploadFile.response.data)
      .then((response)=>{
        if (response.data.code==2001){
          ElMessage.success("服务器文件删除完成!");
        }
      })

}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
/*上传组件结束*/
</script>

<style scoped>

</style>